import { Injectable } from "@nestjs/common";
import { getRandomCode } from "@/shared/utils";
import { UserService } from "../user/user.service";
import dayjs from "dayjs";
import { Result } from "@/common/dto/result.type";
import { SUCCESS,CODE_NOT_EXPIRE,UPDATE_ERROR } from "@/common/constants/code";
@Injectable()
export class AuthService {
    // 这里引入UserService，对UserService的验证码进行更新
    constructor(private readonly userService: UserService) { }
    // 发送短信验证码，但因为没有对应资质，所以这里不做了
    async sendCodeMsg(tel:string): Promise<Result> {
        // console.log(tel)
        const user = await this.userService.findByTel(tel)
        // console.log('user',user)
        if(user){
            const diffTime = dayjs().diff(dayjs(user.codeCreateTimeAt))
            // console.log('diffTime',diffTime)
            if(diffTime<60*1000){
                return {
                    code:CODE_NOT_EXPIRE,
                    message:'code 尚未过期',
                }
            }
            
        }
        const code = getRandomCode();
        try {
            const user = await this.userService.findByTel(tel);
            if(user){
                // 如果存在用户
                const result = await this.userService.updateCode(user.id,code);
                if(result){
                    return {
                        code:SUCCESS,
                        message:'成功',
                    }
                }
                return {
                    code:UPDATE_ERROR,
                    message:'更新失败',
                }
            }
            else{
                // 如果不存在用户
                const result = await this.userService.create({tel,code,codeCreateTimeAt:new Date()})
                if(result){
                    return {
                        code:SUCCESS,
                        message:'成功',
                    }
                }
                return {
                    code:UPDATE_ERROR,
                    message:'新建账号失败',
                }
            }
        } catch (error) {
            console.error(error)
        }
        return new Promise(()=>{return code});
    }
}